package postgres

import (
	"auth/model"
	"auth/model/entity"
	"gorm.io/gorm"
)

var UserAuthority = &userAuthority{}

type userAuthority struct{}

func (a *userAuthority) SetUserAuthorities(userId int64, authorityIds []int64) error {
	return db.Transaction(func(tx *gorm.DB) error {
		TxErr := tx.Delete(&[]entity.UserAuthority{}, "user_id = ?", userId).Error
		if TxErr != nil {
			return TxErr
		}
		if len(authorityIds) == 0 {
			return nil
		}
		var useAuthority []entity.UserAuthority
		for _, v := range authorityIds {
			useAuthority = append(useAuthority, entity.UserAuthority{
				UserId: userId, AuthorityId: v,
			})
		}
		TxErr = tx.Create(&useAuthority).Error
		if TxErr != nil {
			return TxErr
		}
		return nil
	})
}

func (a *userAuthority) Create(m *entity.UserAuthority) (int64, error) {
	err := db.Create(m).Error
	return 0, err
}

func (a *userAuthority) FindByUserId(userId int64) ([]*entity.UserAuthority, error) {
	var userAuthority []*entity.UserAuthority
	err := db.Model(&entity.UserAuthority{}).Find(&userAuthority, "user_id = ?", userId).Error
	return userAuthority, err
}

func (a *userAuthority) FindByAuthorityId(authorityId int64) ([]*entity.UserAuthority, error) {
	var userAuthority []*entity.UserAuthority
	err := db.Model(&entity.UserAuthority{}).Find(&userAuthority, "authority_id = ?", authorityId).Error
	return userAuthority, err
}

func (a *userAuthority) DeleteByUserId(id int64) error {
	return db.Delete(&entity.UserAuthority{}, "user_id=?", id).Error
}

func (a *userAuthority) DeleteByAuthorityId(id int64) error {
	return db.Delete(&entity.UserAuthority{}, "authority_id=?", id).Error
}

func (a *userAuthority) List(in *model.UserAuthorityListRequest) (int, []*entity.UserAuthority, error) {
	var (
		q              = db.Model(&entity.UserAuthority{})
		err            error
		total          int64
		userAuthoritys []*entity.UserAuthority
	)

	if err = q.Count(&total).Error; err != nil {
		return 0, nil, err
	}
	if err = q.Limit(in.Size).Offset((in.Index - 1) * in.Size).Find(&userAuthoritys).Error; err != nil {
		return 0, nil, err
	}
	return int(total), userAuthoritys, nil
}
